package com.yang;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Button;
import android.widget.ProgressBar;

import java.util.Timer;
import java.util.TimerTask;

public class SecondActivity extends AppCompatActivity {

    private ProgressBar progressBar;
    private Button bindServiceBtn, showProgressBtn, continueAddBtn;
    private AddOneService.MyBinder myBinder;
    private MyServiceConnection myServiceConnection;
    private Timer timer;
    private TimerTask timerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        progressBar = findViewById(R.id.progressBar3);
        bindServiceBtn = findViewById(R.id.bindServiceBtn);
        showProgressBtn = findViewById(R.id.showProgressBtn);
        continueAddBtn = findViewById(R.id.continueAddBtn);

        bindServiceBtn.setOnClickListener(view -> {
            Intent intent = new Intent(SecondActivity.this, AddOneService.class);
            myServiceConnection = new MyServiceConnection();
            this.bindService(intent, myServiceConnection, BIND_AUTO_CREATE);
        });

        showProgressBtn.setOnClickListener(view -> {
            if (myBinder != null) {
                timer = new Timer();
                timerTask = new TimerTask() {
                    public void run() {
                        if (myBinder != null) {
                            progressBar.setProgress(myBinder.getProgress());
                        }
                    }
                };
                timer.schedule(timerTask, 0, 100);
            }
        });

        continueAddBtn.setOnClickListener(view -> {
            if (myBinder != null) {
                myBinder.continueAddOne();
            }
        });

    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            myBinder = (AddOneService.MyBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }
}